package com.group.Listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import com.group.pojo.GStudent;
import com.group.pojo.GUser;

@WebListener
public class OnlineListener implements HttpSessionAttributeListener {

    public OnlineListener() {
    }

    public void attributeAdded(HttpSessionBindingEvent se)  {
    	HttpSession session = se.getSession();
    	GUser user = (GUser) session.getAttribute("SESSION_USER");
    	if(user != null && user.getUserID().length() == 12) {
    		GStudent s = new GStudent();
    		s = s.getStudentInfoByID(user.getUserID());
    		Map<String, GStudent> onlineUser = (Map<String, GStudent>) session.getServletContext().getAttribute("onlineUser");
    		if(onlineUser == null) {
    			onlineUser = new HashMap<String, GStudent>();
    		}
    		onlineUser.put(session.getId(), s);
    		session.getServletContext().setAttribute("onlineUser", onlineUser);
    	}
    }

    public void attributeRemoved(HttpSessionBindingEvent se)  {
    	if("SESSION_USER".equals(se.getName())) {
    		HttpSession session = se.getSession();
    		Map<String, GStudent> onlineUser = (Map<String, GStudent>) session.getServletContext().getAttribute("onlineUser");
    		onlineUser.remove(session.getId());
    		session.getServletContext().setAttribute("onlineUser", onlineUser);
    	}
    }

    public void attributeReplaced(HttpSessionBindingEvent se)  { 
    }
	
}
